package net.toby200.canalbuddy.notices;

import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.widget.ArrayAdapter;
import android.widget.SpinnerAdapter;

import net.toby200.canalbuddy.R;

import java.util.logging.Logger;

/**
 * Created by toby on 17/07/2014.
 */
public class ActionBarHelper {

    private static final Logger LOG = Logger.getLogger(MainActivity.class.getName());

    public void setupSpinner(final Activity callingActivity) {

        final Context context = callingActivity.getApplicationContext();

        ActionBar ab = callingActivity.getActionBar();
        ab.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);

        SpinnerAdapter spinner = ArrayAdapter.createFromResource(callingActivity, R.array.screens,
                android.R.layout.simple_spinner_dropdown_item);

        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
        int lastScreen = prefs.getInt(context.getString(R.string.pref_last_screen), 0);
        ab.setSelectedNavigationItem(lastScreen);



        ActionBar.OnNavigationListener navigationCallback = new ActionBar.OnNavigationListener() {
            boolean firstTime = true;

            @Override
            public boolean onNavigationItemSelected(int position, long itemId) {
                LOG.info("onNavigationItemSelected(" + position + ", " + itemId + ")");

                final Context context = callingActivity.getApplicationContext();
                SharedPreferences prefs = callingActivity.getPreferences(Context.MODE_PRIVATE);
                int lastScreen = prefs.getInt(context.getString(R.string.pref_last_screen), -1);

                // first time ever the user runs the app, default to screen 1 and save that as their pref
                // 0 is notice list
                // 1 is map
                if (lastScreen == -1) {
                    lastScreen = 1;
                    LOG.info("No screen preference set, defaulting to screen " + lastScreen);
                    prefs.edit().putInt(context.getString(R.string.pref_last_screen), lastScreen).apply();
                    return true;
                } else if (firstTime) {
                    // app resumed, ignore input event as it's generated by the system rather than user input
                    firstTime = false;
                    return false;
                }

                ((MainActivity)callingActivity).setScreen(position);

                prefs.edit().putInt(context.getString(R.string.pref_last_screen), position).apply();


                return true;
            }
        };

        ab.setListNavigationCallbacks(spinner, navigationCallback);

    }
}